import time

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from config.cfg import *


class StudentOp:

    def studentLogin(self, username, password):
        # 创建 WebDriver 对象
        self.wd = webdriver.Chrome(service=Service(r'/Users/sunlei/Desktop/chromedriver'))
        self.wd.implicitly_wait(10)

        self.wd.get(f'{g_api_server}/student/login/login.html')

        self.wd.find_element(By.ID, "username").send_keys(username)
        self.wd.find_element(By.ID, "password").send_keys(password)
        self.wd.find_element(By.ID, "submit").click()

    # 获取学生主页数据
    def getStuHomePageInfo(self):
        self.wd.find_element(By.CSS_SELECTOR, 'a[href="#/home"] li').click()

        time.sleep(1)

        eles = self.wd.find_elements(By.CSS_SELECTOR, '.row .ng-binding')

        return [ele.text for ele in eles if "注册码" not in ele.text]

    # 学生完成作业
    def doHomeWork(self):

        # 找到'作业通知'元素并悬停鼠标
        homework = self.wd.find_elements(By.CSS_SELECTOR, '.badge-yellow')[0]
        ActionChains(self.wd).move_to_element(homework).perform()

        # 等待动态元素出现, 如已创建作业
        time.sleep(1)

        # 注入JavaScript代码, 5秒后冻结界面
        self.wd.execute_script("setTimeout(function(){debugger}, 5000);")

        # 等待5秒后, 浏览器进入调试模式, 界面被冻住
        time.sleep(5)

        # 点击该作业
        self.wd.find_element(By.CSS_SELECTOR, '.label-blue').click()
        time.sleep(1)

        # 点击 去做
        self.wd.find_elements(By.CSS_SELECTOR, '.btn-outlined')[-1].click()
        time.sleep(1)

        # 选择答案
        elements = self.wd.find_elements(By.CSS_SELECTOR, '.ng-scope .btn-group .btn-choice')
        for ele in elements:
            if ele.text == 'C': # 都选C
                ele.click()

        # 点击提交
        self.wd.find_element(By.CLASS_NAME, 'btn-square').click()
        time.sleep(1)

        # 点击确认
        self.wd.find_elements(By.CSS_SELECTOR, '.btn-primary')[-1].click()

        return True


sop = StudentOp()
